package cn.jiahua.hospital.controller;

import cn.jiahua.hospital.config.OssConfig;
import cn.jiahua.hospital.constants.ResultEnum;
import cn.jiahua.hospital.dto.*;
import cn.jiahua.hospital.pojo.PayDoctor;
import cn.jiahua.hospital.pojo.PayHospital;
import cn.jiahua.hospital.pojo.Report;
import cn.jiahua.hospital.pojo.User;
import cn.jiahua.hospital.service.PayDoctorService;
import cn.jiahua.hospital.service.PayHospitalService;
import cn.jiahua.hospital.service.ReportService;
import cn.jiahua.hospital.service.UserService;
import cn.jiahua.hospital.utils.FileUtils;
import cn.jiahua.hospital.utils.OssUtils;
import cn.jiahua.hospital.utils.RedisUtil;
import cn.jiahua.hospital.utils.ResultUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api
@RequestMapping("/api/user/")
@RestController
public class UserController {

    @Resource
    UserService userService;

    @Resource
    PayDoctorService payDoctorService;

    @Resource
    PayHospitalService payHospitalService;

    @Resource
    RedisUtil redisUtil;

    @Resource
    ReportService reportService;

    @Autowired
    OssUtils ossUtils;

    @Autowired
    OssConfig ossConfig;

    @ApiParam(name = "token", value = "用户token")
    @ApiOperation(value = "获取用户信息", notes = "获取用户个人中心详情信息")
    @GetMapping("getinfo")
    public Result getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FILE_NOT_LOGIN.getCode(), ResultEnum.FILE_NOT_LOGIN.getMsg());
        }
        User user1 = (User) redisUtil.get(token);
        Integer id = user1.getId();
        User user = userService.getUserById(id);
        if (user == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }
        return ResultUtils.returnDataSuccess(user);
    }


    @PostMapping("updateinfo")
    @ApiOperation(value = "修改用户信息", notes = "修改用户个人中心详情信息")
    public Result updateUserInfo(@RequestBody User user,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FILE_NOT_LOGIN.getCode(), ResultEnum.FILE_NOT_LOGIN.getMsg());
        }
        Integer result = userService.qdtxModifyUser(user);
        System.out.println("=========================updateUserInfo  result = "+result);
        if (result <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
        }
        return ResultUtils.returnSuccess();
    }



    @PostMapping("checkPwd")
    @ApiOperation(value = "确认用户密码", notes = "确认用户输入的旧密码是否正确")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPassword", value = "用户旧密码")
    })
    public Result checkPassword(@RequestBody UserDto userDto,HttpServletRequest request) {
        /*Integer id01 = Integer.parseInt(id);*/
        String token = request.getHeader("token");
        if (userDto.getUserPassword() == null || userDto.getUserPassword() == "" || token == null || token == "") {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_PASSWORD.getCode(), ResultEnum.FAIL_USER_PASSWORD.getMsg());
        }
        User user = (User) redisUtil.get(token);

        //1、根据id获取用户的信息
//        User user1 = userService.getUserById(user1.getId());
//        if (user1 == null) {
//            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
//        }
        //2、根据获取到的用户信息判断用户输入的密码是否正确
        if (user.getUserPassword() == "" || !userDto.getUserPassword().equals(user.getUserPassword())) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_PASSWORD.getCode(), ResultEnum.FAIL_USER_PASSWORD.getMsg());
        }
        return ResultUtils.returnSuccess();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "userPassword", value = "用户旧密码", required = true),
            @ApiImplicitParam(name = "userNewPassword", value = "用户新密码", required = true)
    })
    @PostMapping("updatePwd")
    @ApiOperation(value = "修改用户密码", notes = "修改用户密码")
    public Result updatePwd(@RequestBody UserDto userDto,HttpServletRequest request) {
        if (userDto.getId() == null) {
            return ResultUtils.returnFail(ResultEnum.FILE_NOT_LOGIN.getCode(), ResultEnum.FILE_NOT_LOGIN.getMsg());
        }
        //1、根据id获取用户信息
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FILE_NOT_LOGIN.getCode(), ResultEnum.FILE_NOT_LOGIN.getMsg());
        }
        User user = (User) redisUtil.get(token);
        //User user = userService.getUserById(userDto.getId());
        if (user == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        //2、判断用户密码是否正确
        if (!userDto.getUserPassword().equals(user.getUserPassword())) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_PASSWORD.getCode(), ResultEnum.FAIL_USER_PASSWORD.getMsg());
        }
        user.setUserPassword(userDto.getUserNewPassword());
        Integer result = userService.qdtxModifyUser(user);
        if (result <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
        }
        redisUtil.del(token);
        return ResultUtils.returnSuccess();
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页码", required = false),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = false)
    })
    @GetMapping("getPayDoctor")
    @ApiOperation(value = "查看医生关注表信息", notes = "查看个人中心关注医生信息")
    public Result getPayDoctor(Integer pageNo, Integer pageSize,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        User user = (User) redisUtil.get(token);

        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        Page<PayDoctorDto> payDoctor = payDoctorService.getPayDoctorPage(map, pageNo, pageSize);

        return ResultUtils.returnDataSuccess(payDoctor);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页码", required = false),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = false)
    })
    @GetMapping("getPayHospital")
    @ApiOperation(value = "查看医院关注表信息", notes = "查看个人中心关注医院信息")
    public Result getPayHospital(Integer pageNo, Integer pageSize,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        User user = (User) redisUtil.get(token);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        Page<PayHospitalDto> payHospitalPage = payHospitalService.getPayHospitalPage(map, pageNo, pageSize);
        return ResultUtils.returnDataSuccess(payHospitalPage);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "doctorId", value = "医院id", required = true)
    })
    @GetMapping("unfollowDoctor")
    @ApiOperation(value = "取消关注医生", notes = "个人中心取消关注医生信息")
    public Result unfollowDoctor(@RequestParam(value = "userId", required = true) Integer userId,
                                 @RequestParam(value = "doctorId", required = true) Integer doctorId) {
        if (userId == null || doctorId == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        //根据条件获取信息
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("doctorId", doctorId);
        List<PayDoctor> payDoctorListByMap = payDoctorService.getPayDoctorListByMap(map);

        if (payDoctorListByMap == null || payDoctorListByMap.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }
        PayDoctor payDoctor = payDoctorListByMap.get(0);
        Integer payDoctorId = payDoctor.getPayDoctorId();

        //删除关注信息
        Integer integer = payDoctorService.qdtxDeletePayDoctorById(payDoctorId);

        if (integer <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
        }
        return ResultUtils.returnSuccess();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "hospitalId", value = "医院id", required = true)
    })
    @GetMapping("unfollowHospital")
    @ApiOperation(value = "取消关注医院", notes = "个人中心取消关注医院信息")
    public Result unfollowHospital(@RequestParam(value = "userId", required = true) Integer userId,
                                   @RequestParam(value = "hospitalId", required = true) Integer hospitalId) {
        if (userId == null || hospitalId == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        //根据条件获取信息
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("hospitalId", hospitalId);
        List<PayHospital> payHospitalListByMap = payHospitalService.getPayHospitalListByMap(map);

        if (payHospitalListByMap == null || payHospitalListByMap.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }
        PayHospital payHospital = payHospitalListByMap.get(0);
        Integer payHospitalId = payHospital.getPayHospitalId();
        //删除关注信息
        Integer integer = payHospitalService.qdtxDeletePayHospitalById(payHospitalId);

        if (integer <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
        }
        return ResultUtils.returnSuccess();
    }


    @ApiOperation(value = "查看报告信息", notes = "用户个人中心查看报告信息")
    @ApiImplicitParam(name = "orderId", value = "订单编号")
    @GetMapping("report")
    public Result getReport(Integer orderId) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        List<Report> reportListByMap = reportService.getReportListByMap(map);
        if (reportListByMap == null || reportListByMap.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }
        return ResultUtils.returnDataSuccess(reportListByMap);
    }

    @ApiOperation(value = "下载报告信息", notes = "用户个人中心下载报告信息")
    @ApiImplicitParam(name = "orderId", value = "订单编号")
    @GetMapping("downReport")
    public Result downReport(Integer orderId) {
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        List<Report> reportListByMap = reportService.getReportListByMap(map);
        if (reportListByMap == null || reportListByMap.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }
        return ResultUtils.returnDataSuccess(reportListByMap);
    }
    //
    @ApiOperation(value = "用户文件上传", notes = "用户修改头像")
    @PostMapping("/uploadfile")
    public Result uploadFile(@RequestParam MultipartFile file, HttpServletRequest request) {
        try {
            String fileName = UUID.randomUUID().toString().substring(0,6) +file.getOriginalFilename();
            String filePath = "hospital/user/";
            //1、将multipartfile转化为file
            File fileInfo = FileUtils.MultipartFileToFile(file);
            String result = ossUtils.uploadByStream(fileInfo, filePath + fileName);
            //删除原有的图片，判断图片是oss文件或者是微信头像
            String token = request.getHeader("token");
            if (token == null) {
                return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
            }
            User user2 = (User) redisUtil.get(token);
            User user1 = userService.getUserById(user2.getId());
            String userWeChatHead = user1.getUserWeChatHead();
            String substring = userWeChatHead.substring(0, 25);
            if ("https://jt98-hospital.oss".equals(substring)){
                boolean b = ossUtils.delFile(ossConfig.getBucketName(), userWeChatHead.substring(51));
                if (!b){
                    return ResultUtils.returnFail("上传图片失败,原文件删除异常");
                }
            }
            User user = new User();
            user.setUserWeChatHead(ossConfig.getOssWebUrl() + filePath + fileName);
            user.setId(user2.getId());
            userService.qdtxModifyUser(user);
            return ResultUtils.returnDataSuccess("上传文件成功");
        }catch (Exception ex){
            ex.printStackTrace();
            return ResultUtils.returnFail("出现异常，查看日志");
        }
    }
}
